<?php
/**
* @file $Id: Student.php 437 2007-04-23 00:57:51Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/

$db_date = DBDate();
$user_syear = UserSyear();
$user_school = UserSchool(); 
$user_profile = User('PROFILE');
$user_username = User('USERNAME');
$user_student_id = UserStudentID();
$user_profile_id = User('PROFILE_ID');

// $_REQUEST['include'] means : what module do I include, aka, what student "page" should be displayed in the body of this form?

// When they first select this page, select an appropriate default tab.
if (!$_REQUEST['include']) {
	$_REQUEST['category_id'] = Preferences('DEFAULT_TAB');
	switch($_REQUEST['category_id']) {
		case 1:	$_REQUEST['include'] = 'General_Info';	break;
		case 2:	$_REQUEST['include'] = 'Medical';		break;
		case 3:	$_REQUEST['include'] = 'Address';		break;
		default:$_REQUEST['include'] = 'Other_Info';	break;
	}
}

// I dont know why this needs to be here, but I wont remove it without thinking it through - BL
if (!$_REQUEST['category_id'] 
&&  $_REQUEST['include'] == 'Address'
){
	$_REQUEST['category_id'] = 3;
}

// Teachers can edit things in some pages, decide if they can edit this page.
if ($user_profile == 'teacher'
&&  'Y' == DBGetValue("
			SELECT       sfc.ALLOW_TEACHER_MODIFY as VALUE
			FROM         STUDENT_FIELD_CATEGORIES sfc 
			WHERE        sfc.ID = '$_REQUEST[category_id]'
			")
){
	$_FOCUS['allow_edit'] = true;
}

// when $_REQUEST['modfunc'] == 'update' they have clicked submit on some form, and we need to apply database changes.
if ($_REQUEST['modfunc'] == 'update' 
&&  AllowEdit()
){
	if (count($_REQUEST['month_students'])) {
		foreach ($_REQUEST['month_students'] as $column => $value) {
			$_REQUEST['students'][$column] // =
					=	$_REQUEST['day_students'][$column]
					   . '-'
					   . $_REQUEST['month_students'][$column]
					   . '-'
					   . $_REQUEST['year_students'][$column]
					  ;

			if ($_REQUEST['students'][$column] == '--') {
				$_REQUEST['students'][$column] = '';
			}
			elseif (!VerifyDate($_REQUEST['students'][$column])) {
				unset($_REQUEST['students'][$column]);
				$note = _("The invalid date could not be saved.");
			}
		}
	}
	unset($_REQUEST['day_students']); 
	unset($_REQUEST['month_students']); 
	unset($_REQUEST['year_students']);

	if ((count($_REQUEST['students']) || count($_REQUEST['values'])) 
	&&  AllowEdit()
	){
		if ($_REQUEST['student_id'] 
		&&  $_REQUEST['student_id'] != 'new'
		){
			if (count($_REQUEST['students'])) {
				$sql = "UPDATE STUDENTS SET ";
				foreach ($_REQUEST['students'] as $column_name => $value) {
					if (!is_array($value)) {
						$sql .= "$column_name='"
								. str_replace("\'", "''"
								, str_replace('``', '"', $value))
								. "',"
								;
					}
					else {
						$sql .= $column_name."='||";
						foreach ($value as $val) {
							if ($val) {
								$sql .= str_replace("\'","''"
									  , str_replace('``', '"', $val)) . '||';
							}
						}
						$sql .= "',";
					}
				}				
				$sql = substr($sql,0,-1) . " WHERE STUDENT_ID='$_REQUEST[student_id]'";
				DBQuery($sql);
			}

			if (count($_REQUEST['values']['STUDENT_ENROLLMENT'][$user_student_id])) {
				$sql = "UPDATE STUDENT_ENROLLMENT SET ";
				foreach ($_REQUEST['values']['STUDENT_ENROLLMENT'][$user_student_id] as $column_name => $value) {
					$sql .= "$column_name='"
							. str_replace("\'", "''"
							, str_replace("&rsquo;", "''", $value))
							. "',"
							;
				}
				
				$sql = substr($sql,0,-1) . " 
					WHERE  STUDENT_ID = '$_REQUEST[student_id]' 
					AND   SYEAR = '$user_syear' 
					AND   SCHOOL_ID = '$user_school'
				";
				
				DBQuery($sql);
			}
		}
		else {
			$required_violation = 0;
			if (!$_REQUEST['students']['LAST_NAME']) {
				$required_violation++;
				$required_text .= _('Last Name').', ';
			}
			
			if (!$_REQUEST['values']['STUDENT_ENROLLMENT']['new']['GRADE_ID']) {
				$required_violation++;
				$required_text .= _('Grade').', ';
			}
			
			if (!$_REQUEST['values']['STUDENT_ENROLLMENT']['new']['CALENDAR_ID']) {
				$cal_RET = DBGet(DBQuery("
					SELECT       TITLE 
					FROM         ATTENDANCE_CALENDARS 
					WHERE        SYEAR = '$user_syear' 
					 AND         SCHOOL_ID = '$user_school'
				"));

				if (count($cal_RET)) {
					$required_violation++;
					$required_text .= _('Calendar') . ', ';
				}
			}
			
			$required_fields_RET = DBGet(DBQuery("SELECT ID,TITLE FROM CUSTOM_FIELDS WHERE TYPE != 'radio' AND REQUIRED='Y'"));
			foreach ($required_fields_RET as $field) {
				if (!$_REQUEST['students']['CUSTOM_'.$field['ID']]) {
					$required_violation++;
					$required_text .= $field['TITLE'].', ';
				}
			}

			if ($required_violation == 1) {
				BackPrompt(_('The student was not added since')
						. ' '
						. substr($required_text,0,-2)
						. ' '
						. _('is a required field.  Please fix this and try again.')
						);
			}
			elseif ($required_violation) {
				BackPrompt(_('The student was not added since the following fields are required:')
						. ' '
						. substr($required_text,0,-2)
						. '. '
						. _('Please fix these fields and try again.')
						);
			}

			if ($_REQUEST['assign_student_id']) {
				$student_id = $_REQUEST['assign_student_id'];
				if (count(DBGet(DBQuery("
					SELECT        STUDENT_ID 
					FROM          STUDENTS 
					WHERE         STUDENT_ID = '$student_id'
					")))
				){
					BackPrompt(_('That Student ID is already taken. Please select a different one.'));
				}
			}
			else {
				do {
					$student_id = DBGet(DBQuery('
						SELECT ' . db_seq_nextval('STUDENTS_SEQ') . ' AS STUDENT_ID '
						. FROM_DUAL
						));
					$student_id = $student_id[1]['STUDENT_ID'];
				} while(count(DBGet(DBQuery("
					SELECT       STUDENT_ID 
					FROM         STUDENTS 
					WHERE        STUDENT_ID = '$student_id'
					"))));
			}

			if ($_REQUEST['students']['USERNAME']) {
				$username = $_REQUEST['students']['USERNAME'];
				$i = '';
				do {
					$_REQUEST['students']['USERNAME'] = $username.$i;
					$i++;
				} while(count(DBGet(DBQuery("
							SELECT        STUDENT_ID 
							FROM          STUDENTS 
							WHERE         USERNAME = '"
										. $_REQUEST['students']['USERNAME']."'
							"))) 
						|| count(DBGet(DBQuery("
							SELECT        '' 
							FROM          USERS 
							WHERE         USERNAME='"
										. $_REQUEST['students']['USERNAME']."'
							")))
						);
			}
			
			// "INSERT INTO STUDENTS "
			$fields = 'STUDENT_ID,';
			$values = "'$student_id',";

			foreach ($_REQUEST['students'] as $column => $value) {
				if ($value) {
					$fields .= $column.',';
					if (!is_array($value)) {
						$values .= "'" . str_replace("\'", "''", $value) . "',";
					}
					else {
						$values .= "'||";
						foreach ($value as $val){
							if ($val) {
								$values .= $val.'||';
							}
						}
						$values .= "',";
					}
				}
			}
			
			$fields = substr($fields, 0, -1);
			$values = substr($values, 0, -1);
			DBQuery("
				INSERT INTO STUDENTS
				( $fields )
				values 
				( $values )
				");

			// INSERT INTO STUDENT_ENROLLMENT
			$fields = 'ID
					, STUDENT_ID
					, SYEAR
					, SCHOOL_ID
					,'
					;
			$values = db_seq_nextval('STUDENT_ENROLLMENT_SEQ') . "
					, '$student_id'
					, '$user_syear'
					, '$user_school'
					,"
					;

			$_REQUEST['values']['STUDENT_ENROLLMENT']['new']['START_DATE'] // = 
				= $_REQUEST['day_values']['STUDENT_ENROLLMENT']['new']['START_DATE']
				. '-'
				. $_REQUEST['month_values']['STUDENT_ENROLLMENT']['new']['START_DATE']
				. '-'
				. $_REQUEST['year_values']['STUDENT_ENROLLMENT']['new']['START_DATE']
				;

			foreach ($_REQUEST['values']['STUDENT_ENROLLMENT']['new'] as $column => $value) {
				if ($value) {
					$fields .= $column . ',';
					$values .= "'" . str_replace("\'", "''", $value) . "',";
				}
			}
			
			// trim off that trailing comma
			$fields = substr($fields, 0, -1);
			$values = substr($values, 0, -1);
			
			DBQuery("
				INSERT INTO STUDENT_ENROLLMENT
				( $fields )
				values 
				( $values )
				");

			$_REQUEST['student_id'] = $student_id;
			$_SESSION['student_id'] = $student_id;
			$new_student = true;
		}
	}

	if ($_REQUEST['log_values'] 
	&&  $_POST['log_values']
	){
		if (count($_REQUEST['month_log_values'])){
			foreach ($_REQUEST['month_log_values'] as $student_field_id => $records) {
				foreach ($records as $id => $columns) {
					foreach ($columns as $field_name => $month) {
						$_REQUEST['log_values'][$student_field_id][$id][$field_name] // =
							= $_REQUEST['day_log_values'][$student_field_id][$id][$field_name]
							. '-'
							. $month
							. '-' 
							. $_REQUEST['year_log_values'][$student_field_id][$id][$field_name]
							;
							
						if (!VerifyDate($_REQUEST['log_values'][$student_field_id][$id][$field_name])) {
							if ($_REQUEST['log_values'][$student_field_id][$id][$field_name] != '--') {
								$note = '<img src=assets/warning_button.gif>'
										. _('The date you specified is not valid, so was not used.  The other data was saved.');
							}
							unset($_REQUEST['log_values'][$student_field_id][$id][$field_name]);
						}
					}
				}
			}
		}
		
		foreach ($_REQUEST['log_values'] as $student_field_id => $records) {
			foreach ($records as $id => $columns) {
				if ($id != 'new') {
					$sql = "UPDATE STUDENT_LOG_ENTRIES SET ";

					if (count($columns)) {
						foreach ($columns as $column => $value) {
							$sql .= "$column='" 
								. str_replace("\'", "''", $value)
								. "',";
						}
						
						$sql = substr($sql, 0, -1) . " WHERE ID='$id'";
						DBQuery($sql);
					}
				}
				else {
//					"INSERT INTO STUDENT_LOG_ENTRIES ";

					$fields = "ID
							, SCHOOL_ID
							, STUDENT_ID
							, STUDENT_FIELD_ID
							,";
					$values = db_seq_nextval('STUDENT_LOG_ENTRIES_SEQ') . "
							, '$user_school'
							, '$user_student_id'
							, '$student_field_id'
							,";

					$go = 0;
					foreach ($columns as $column => $value) {
						if ($value) {
							$fields .= " $column
							,";
							
							$values .= "'" . str_replace("\'", "''", $value)."'
							,";
							
							if ($column != 'LOG_DATE') // SINCE THE LOG_DATE HAS A DEFAULT
								$go = true;
						}
					}
					
					$sql .= '(' .  . ') values(' .  . ')';

					if ($go) {
						$fields = substr($fields,0,-1);
						$values = substr($values,0,-1);
						DBQuery("
							INSERT INTO STUDENT_LOG_ENTRIES
							( $fields )
							VALUES
							( $values )						
							");
					}
				}
			}
		}
	}

	unset($_REQUEST['modfunc']);
	// SHOULD THIS BE HERE???
	if (!$user_student_id) {
		unset($_REQUEST['values']);
	}
	unset($_SESSION['_REQUEST_vars']['modfunc']);
	unset($_SESSION['_REQUEST_vars']['values']);
}

if ($_REQUEST['student_id'] == 'new') {
	// So the HeaderIcon is set
	ProgramTitle();
	DrawHeader(_('Add a Student'));
}
else {
	DrawHeader(ProgramTitle());
}

Widgets('all');
Search('student_id',$extra);

if ($user_student_id 
||  $_REQUEST['student_id'] == 'new'
){
	if ($_REQUEST['modfunc'] != 'delete' 
	||  $_REQUEST['delete_ok'] == '1'
	){
		if ($_REQUEST['student_id'] != 'new') {
			DrawStudentHeader();
			$student = DBGetRow("
					SELECT       s.STUDENT_ID
					 ,           s.FIRST_NAME
					 ,           s.LAST_NAME
					 ,           s.MIDDLE_NAME
					 ,           s.NAME_SUFFIX
					 ,			 ssm.SCHOOL_ID
					 ,           ssm.GRADE_ID
					 ,           s.USERNAME
					 ,           s.PASSWORD
					 ,           s.PROFILE_ID
					FROM         STUDENTS s
					 JOIN        STUDENT_ENROLLMENT ssm
					  ON         ssm.STUDENT_ID = s.STUDENT_ID
					WHERE        s.STUDENT_ID = '$user_student_id' 
					 AND         ssm.SYEAR = '$user_syear' 
					ORDER BY     ssm.START_DATE DESC
					 ,           ssm.END_DATE DESC
					");
			$school = DBGet(DBQuery("
					SELECT       SCHOOL_ID
					 ,           GRADE_ID 
					FROM         STUDENT_ENROLLMENT 
					WHERE        STUDENT_ID = '$user_student_id'
					 AND         SYEAR = '$user_syear' 
					 AND (       '$db_date' BETWEEN START_DATE AND END_DATE 
					  OR         END_DATE IS NULL )
					"));
					
			$_REQUEST['modname'] = str_replace(   '?student_id=new'
												, ''
												, $_REQUEST['modname']
											);
											
			echo "<form name='student' 
					action=\"Modules.php"
					. "?modname=$_REQUEST[modname]"
					. "&include=$_REQUEST[include]"
					. "&student_id=$user_student_id"
					. "&category_id=$_REQUEST[category_id]"
					. "&LO_index=$_REQUEST[LO_index]"
					. "&modfunc='update'\" 
					method='POST'>";
		}
		else {
			echo "<form name='student' 
					action=\"Modules.php"
					. "?modname=$_REQUEST[modname]"
					. "&include=$_REQUEST[include]"
					. "&LO_index=$_REQUEST[LO_index]"
					. "&modfunc=update\"
					method='POST'>";
		}
		$name = $student['FIRST_NAME']
				. ' '
				. $student['MIDDLE_NAME']
				. ' '
				. $student['LAST_NAME']
				. ' '
				. $student['NAME_SUFFIX']
				;

		if ($_REQUEST['student_id'] != 'new') {
			$name .= ' - ' . $student['STUDENT_ID'];
		}
		
		if ($_REQUEST['category_id'] == '1' 
		&& AllowUse('Students/DeleteStudent.php')
		){
			$attendance_RET = DBGet(DBQuery("
				SELECT       COUNT(*) AS COUNT 
				FROM         ATTENDANCE_PERIOD 
				WHERE        STUDENT_ID = '$user_student_id'
				"));
				
			$grades_RET = DBGet(DBQuery("
				SELECT       COUNT(*) AS COUNT 
				FROM         STUDENT_REPORT_CARD_GRADES 
				WHERE        STUDENT_ID = '$user_student_id'
				"));

			if ($grades_RET[1]['COUNT'] > 0 
			|| $attendance_RET[1]['COUNT'] > 0
			){
				$disabled = ' DISABLED';
			}
			
			$delete_button = "<input type='button' 
									value='" . _('Delete') . "'
									$disabled 
									onclick=\"window.location='"
										. "Modules.php"
										. "?modname=Students/DeleteStudent.php"
										. "&student_id=$user_student_id'
								/> &nbsp; ";
		}
		
		DrawHeader($name, $delete_button . SubmitButton(_('Save')));

		//echo '</TD></TR></TABLE>';
		//array('title' => 'Emergency','link' => "Modules.php?modname=$_REQUEST[modname]&include=EmergencyReport")

		if (User('PROFILE') == 'admin' 
		||  true
		){
			if (is_numeric(User('PROFILE_ID'))) {				
				$can_use_RET = DBGet(DBQuery("
					SELECT       MODNAME 
					FROM         PROFILE_EXCEPTIONS 
					WHERE        PROFILE_ID = '$user_profile_id' 
					 AND         CAN_USE = 'N'
					"), array(), array('MODNAME'));
			}
			else {
				$can_use_RET = DBGet(DBQuery("
					SELECT       MODNAME 
					FROM         USER_EXCEPTIONS 
					WHERE        USERNAME = '$user_username' 
					 AND         CAN_USE='N'
					"), array(), array('MODNAME'));
			}
		}
		
		if (!$can_use_RET['Students/Student.php&category_id=1']) {
			$tabs[] = array(  'title' => _('General Info')
							, 'link'  => "Modules.php"
										. "?modname=$_REQUEST[modname]"
										. "&include=General_Info"
										. "&category_id=1"
										. "&LO_index=$_REQUEST[LO_index]"
							);
		}
		
		if (!$can_use_RET['Students/Student.php&category_id=3']) {
			$tabs[] = array(  'title' => _('Addresses & Contacts')
							, 'link'  => "Modules.php"
										. "?modname=$_REQUEST[modname]"
										. "&include=Address"
										. "&category_id=3"
										. "&LO_index=$_REQUEST[LO_index]"
							);
		}

		$categories_RET = DBGet(DBQuery("
			SELECT       ID
			 ,           TITLE 
			FROM         STUDENT_FIELD_CATEGORIES 
			WHERE        ID != 1 
			 AND         ID != 3 
			ORDER BY     SORT_ORDER
			 ,           TITLE
			"));

		foreach ($categories_RET as $category) {
			if (!$can_use_RET["Students/Student.php&category_id=$category[ID]"]) {
				$tabs[] = array(  'title' => $category['TITLE']
								, 'link'  => "Modules.php"
											. "?modname=$_REQUEST[modname]"
											. "&include=Other_Info"
											. "&category_id=$category[ID]"
											. "&LO_index=$_REQUEST[LO_index]"
								);
			}
		}

		$_FOCUS['selected_tab'] = "Modules.php"
									. "?modname=$_REQUEST[modname]"
									. "&include=$_REQUEST[include]"
									;

		if ($_REQUEST['category_id']) {
			$_FOCUS['selected_tab'] .= "&category_id=$_REQUEST[category_id]"
									.  "&LO_index=$_REQUEST[LO_index]"
									;
		}
		
		echo '<br />';
		
		if (Preferences('MENU') == 'Top') {
			$width = 'width=95%';
		}
		else {
			$width = 'width=99%';
		}
		
		if ($_REQUEST['student_id'] == 'new') {
			$tabs = array($tabs[0]);
			unset($tabs[0]['link']);
		}
		
		echo PopTable('header', $tabs, $width);

		include($staticpath 
					. "modules/Students/includes/$_REQUEST[include].inc.php"
				);
										
		echo '<br /><center>' . SubmitButton(_('Save')) . '</center>';
		echo PopTable('footer');
		echo '</form>';
	}
	else {
		include("modules/Students/includes/$_REQUEST[include].inc.php");
	}
}
?>